package com.ruoyi.commodity.service.impl;


import com.ruoyi.commodity.domain.CommodityType;
import com.ruoyi.commodity.domain.vo.CommodityTypeQueryVo;
import com.ruoyi.commodity.mapper.CommodityTypeMapper;
import com.ruoyi.commodity.service.ICommodityTypeService;
import com.ruoyi.common.core.constant.CommodityConstants;
import com.ruoyi.common.core.constant.UserConstants;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.core.utils.SpringUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.commodity.domain.vo.TreeSelect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service

public class CommodityTypeServiceImpl implements ICommodityTypeService {

    @Autowired
    public CommodityTypeMapper commodityTypeMapper;


    @Override
    public boolean checkCommodityTypeNameUnique(CommodityType commodityType) {
        Long commodityTypeId = StringUtils.isNull(commodityType.getCommodityTypeId()) ? -1L :commodityType.getCommodityTypeId();
        CommodityType commodityCheck =  commodityTypeMapper.checkCommodityTypeNameUnique(commodityType.getCommodityTypeName());
        if (commodityCheck != null && !Objects.equals(commodityCheck.getCommodityTypeId(), commodityTypeId)) {
            return CommodityConstants.NOT_UNIQUE;
        }
        return CommodityConstants.UNIQUE;
    }

    @Override
    public int insertCommodityType(CommodityType commodityType) {
        if(commodityType.getParentId()==0){
            commodityType.setAncestors("0");
            return commodityTypeMapper.insertCommodityType(commodityType);
        }else{
            CommodityType info = commodityTypeMapper.selectCommodityTypeById(commodityType.getParentId());
            // 如果父节点不为正常状态,则不允许新增子节点
            if (!CommodityConstants.TYPE_NORMAL.equals(info.getStatus()))
            {
                throw new ServiceException("商品类型停用，不允许新增");
            }
            commodityType.setAncestors(info.getAncestors() + "," + commodityType.getParentId());
            return commodityTypeMapper.insertCommodityType(commodityType);
        }
    }


    @Override
    public CommodityType selectCommodityTypeById(Long commodityTypeId) {
        return commodityTypeMapper.selectCommodityTypeById(commodityTypeId);
    }

    @Override
    public List<CommodityType> selectCommodityTypeList(CommodityTypeQueryVo commodityTypeQueryVo) {
        return commodityTypeMapper.selectCommodityTypeList(commodityTypeQueryVo);
    }


    /**
     * 查询部门树结构信息
     *
     * @param
     * @return commodity树信息集合
     */
    @Override
    public List<TreeSelect> selectCommodityTreeList(CommodityTypeQueryVo commodityTypeQueryVo){
        List<CommodityType> list = SpringUtils.getAopProxy(this).selectCommodityTypeList(commodityTypeQueryVo);
        return buildCommodityTypeTreeSelect(list);
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @param
     * @return 下拉树结构列表
     */
    @Override
    public List<TreeSelect> buildCommodityTypeTreeSelect(List<CommodityType> list)
    {
        List<CommodityType> commodityTypeTrees = buildCommodityTypeTree(list);
        return commodityTypeTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    /**
     * 构建前端所需要树结构
     *
     * @param
     * @return 树结构列表
     */
    @Override
    public List<CommodityType> buildCommodityTypeTree(List<CommodityType> list) {
        List<CommodityType> returnList = new ArrayList<>();
        List<Long> tempList = list.stream().map(CommodityType::getCommodityTypeId).collect(Collectors.toList());
        for (CommodityType commodityType : list)
        {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(commodityType.getParentId()))
            {
                recursionFn(list, commodityType);
                returnList.add(commodityType);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = list;
        }
        return returnList;
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<CommodityType> list, CommodityType t)
    {
        // 得到子节点列表
        List<CommodityType> childList = getChildList(list, t);
        t.setChildren(childList);
        for (CommodityType tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<CommodityType> getChildList(List<CommodityType> list, CommodityType t)
    {
        List<CommodityType> tlist = new ArrayList<>();
        Iterator<CommodityType> it = list.iterator();
        while (it.hasNext())
        {
            CommodityType n = it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getCommodityTypeId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    private boolean hasChild(List<CommodityType> list, CommodityType t) {
        return getChildList(list, t).size() > 0 ? true : false;
    }

    @Override
    public int selectNormalChildrenCommodityTypeById(Long commodityTypeId){
        return commodityTypeMapper.selectNormalChildrenCommodityTypeById(commodityTypeId);
    }

/**
 * 是否存在子节点
 */

    @Override
    public boolean hasChildByCommodityTypeId(Long commodityTypeId)
    {
        int result = commodityTypeMapper.hasChildByCommodityTypeId(commodityTypeId);
        return result > 0;
    }

    @Override
    public int updateCommodityType(CommodityType commodityType) {
        CommodityType newParentCommodityType = commodityTypeMapper.selectCommodityTypeById(commodityType.getParentId());
        CommodityType oldCommodityType = commodityTypeMapper.selectCommodityTypeById(commodityType.getCommodityTypeId());
        if (StringUtils.isNotNull(newParentCommodityType) && StringUtils.isNotNull(oldCommodityType))
        {
            String newAncestors = newParentCommodityType.getAncestors() + "," + newParentCommodityType.getCommodityTypeId();
            String oldAncestors = oldCommodityType.getAncestors();
            commodityType.setAncestors(newAncestors);
            updateCommodityTypeChildren(commodityType.getCommodityTypeId(), newAncestors, oldAncestors);
        }
        System.out.println("!!!!!!!!!!!!"+commodityType.getStatus());
        int result = commodityTypeMapper.updateCommodityType(commodityType);
        if (CommodityConstants.TYPE_NORMAL.equals(commodityType.getStatus()) && StringUtils.isNotEmpty(commodityType.getAncestors())
                && !StringUtils.equals("0", commodityType.getAncestors()))
        {
            // 如果该部门是启用状态，则启用该部门的所有上级部门
            updateParentCommodityTypeStatusNormal(commodityType);
        }
        return result;
    }

    @Override
    public int deleteCommodityTypeById(Long commodityTypeId) {
        return commodityTypeMapper.deleteCommodityTypeById(commodityTypeId);
    }

    public void updateCommodityTypeChildren(Long CommodityTypeId, String newAncestors, String oldAncestors)
    {
        List<CommodityType> children = commodityTypeMapper.selectChildrenCommodityTypeById(CommodityTypeId);
        for (CommodityType child : children)
        {
            child.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
        }
        if (children.size() > 0)
        {
            commodityTypeMapper.updateCommodityTypeChildren(children);
        }
    }

    /**
     * 修改该部门的父级部门状态
     *
     * @param
     */
    private void updateParentCommodityTypeStatusNormal(CommodityType commodityType)
    {
        System.out.println("!!!!!!!!!!!!!!!!!!!!!!"+commodityType.getStatus());
        String ancestors = commodityType.getAncestors();
        Long[] CommodityTypeIds = Convert.toLongArray(ancestors);
        commodityTypeMapper.updateCommodityTypeStatusNormal(CommodityTypeIds);
    }


}
